package com.pmcc.yn.service;
import com.pmcc.utils.*;
import com.pmcc.yn.entity.EvaluateInfo;
import com.pmcc.yn.entity.OrderList;
import com.pmcc.yn.entity.StoreInfo;
import com.pmcc.yn.repository.EvaluateInfoRepository;
import com.pmcc.yn.repository.OrderListRepository;
import com.pmcc.yn.repository.StoreInfoRepository;
import com.pmcc.yn.vo.EvaluateInfoVo;
import com.pmcc.yn.vo.EvaluateVo;
import com.pmcc.yn.vo.FeedBackVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by chuxuyang on 2019/1/12.
 */
@Service
@Transactional
public class EvaluateInfoService {

     @Autowired
     EvaluateInfoRepository repository;
     @Autowired
     OrderListRepository orderListRepository;
     @Autowired
     StoreInfoRepository storeInfoRepository;


    @Value("${web.downloadFile}")
    private  String downloadFile;

    public ResultBean showList(AntdPage antdPage , EvaluateInfo model) throws Exception{
        ResultBean resultBean=new ResultBean();
        Page page=repository.findAll(this.getSpecification(model),antdPage.getPageRequest());

        resultBean.setPage(antdPage.getDefaultCurrent());
        resultBean.setTotal(page.getTotalElements());
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setPageSize(antdPage.getPageSize());
        resultBean.setRows(page.getContent());
        return resultBean;
    }
    public Specification<EvaluateInfo> getSpecification(EvaluateInfo model) {
        return new Specification<EvaluateInfo>() {
            @Override
            public Predicate toPredicate(Root<EvaluateInfo> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }
    /**
     * 新增
     * @return
     */
    public ResultBean add(EvaluateInfo model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try{
            model.setEvaluateTime(new Date());
            repository.saveAndFlush(model);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setResultDesc("新增成功");
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    /**
     * 修改
     * @param map
     * @return
     */
    public ResultBean update(Map map) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            EvaluateInfo c = repository.findById(map.get("id").toString());
            BeanUtils.setBeanData(c,map);
            repository.saveAndFlush(c);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(c);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public ResultBean deleteById(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            repository.delete(id);
            resultBean.setResultCode(ResultBean.SUCCESS);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean orderAppraise(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            EvaluateInfo evaluateInfo = repository.findByOrderId(id);
            FeedBackVo vo = new FeedBackVo();
            //评分
            vo.setScore(evaluateInfo.getScore());
            //评价
            vo.setContent(evaluateInfo.getCommentContent());
            //图片
            vo.setPic1(evaluateInfo.getPicAddress1());
            vo.setPic2(evaluateInfo.getPicAddress2());
            vo.setPic3(evaluateInfo.getPicAddress3());
            //查找订单
            OrderList orderList = orderListRepository.findById(id);
            //门店名称
            vo.setStoreName(orderList.getStoreName());
            //赏金
            vo.setMoney(orderList.getMoney());
            //任务时间
            vo.setPreTime(orderList.getPreTime());
            //服务类型
            vo.setSerType(orderList.getSerType());
            //查找门店
            StoreInfo storeInfo = storeInfoRepository.findById(orderList.getStoreId());
            //负责人
            vo.setLeader(storeInfo.getLeader());
            //门店地址
            vo.setAddress(storeInfo.getAddress());
            //门店联系方式
            vo.setPhone(storeInfo.getPhone());
            resultBean.setObject(vo);
        }catch (Exception e){
            resultBean.setResultDesc(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean goAppraise(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            OrderList orderList = orderListRepository.findById(id);
            StoreInfo storeInfo = storeInfoRepository.findById(orderList.getStoreId());
            EvaluateVo vo = new EvaluateVo();
            //订单id
            vo.setOrderId(id);
            //门店id
            vo.setStoreId(storeInfo.getId());
            //门店联系电话
            vo.setPhone(storeInfo.getPhone());
            //门店名称
            vo.setStoreName(storeInfo.getName());
            //门店地址
            vo.setAddress(storeInfo.getAddress());
            resultBean.setObject(vo);
        }catch (Exception e){
            resultBean.setResultDesc(ResultBean.FAIL);
        }
        return resultBean;
    }
    //上传图片
    public String upload(MultipartFile file) {
        // 上传的文件存放路径
        String uploadDiskPath = downloadFile;
        if (!file.isEmpty()) {
            try {
                String originalFilename = new String(file.getOriginalFilename());
                String[] arr = originalFilename.split("\\.");
                // 文件类型
                String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
                // 存放在服务器端的文件名
                String serverFileName = fileType == "" ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;
                // 创建文件夹  年-月-日/goods
                String folder = "/" + DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
                // 数据库存放路径：年-月-日/文件名
                String fileUrl = "/" + folder + "/" + serverFileName;

//                Employee employee = employeeRepository.findById(employeeId);
//                employee.setPhoto("/downloadFile"+fileUrl);
//                employeeRepository.saveAndFlush(employee);
                File targetFile = new File(uploadDiskPath, fileUrl);
                if (!targetFile.exists()) {
                    targetFile.getParentFile().mkdir();
                    targetFile.createNewFile();
                }
                file.transferTo(targetFile);
                return fileUrl;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                //return "上传失败," + e.getMessage();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                //return "上传失败," + e.getMessage();
                return null;
            }
//            return "上传成功";
        } else {
            return null;
        }
    }

    public ResultBean storeAppraise(String id, String orderId, String storeId, Double score, String appraise, MultipartFile file1, MultipartFile file2, MultipartFile file3) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            EvaluateInfo evaluateInfo = new EvaluateInfo();
            evaluateInfo.setCommentContent(appraise);
            evaluateInfo.setScore(score);
            evaluateInfo.setEvaluatorId(id);
            evaluateInfo.setOrderId(orderId);
            evaluateInfo.setBeEvaluatorId(storeId);
            evaluateInfo.setOrderType("门店评价");
            evaluateInfo.setPicAddress1(this.upload(file1));
            evaluateInfo.setPicAddress2(this.upload(file2));
            evaluateInfo.setPicAddress3(this.upload(file3));
            this.add(evaluateInfo);
        }catch (Exception e){
            resultBean.setResultDesc(ResultBean.FAIL);
        }
        return resultBean;
    }

}
